﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml;
using System.Globalization;
using System.Xml.Linq;

namespace AllTalk
{
    internal class ChatMessage
    {
        public static string MessageType = "chat";
        public string Message { get; set; }
        public DateTime Timestamp { get; set; }
        public Jid Sender { get; set; }
        public Jid Recepient { get; set; }
        
        public string ToXml()
        {
            string messageXml = @"<message from=""{0}"" to=""{1}"" type=""{2}""><body>{3}</body></message>";
            return String.Format(CultureInfo.InvariantCulture,
                messageXml,
                Sender.ToString(), 
                Recepient.ToString(),
                MessageType,
                HttpUtility.HtmlEncode(this.Message));
        }
        
        internal ChatMessage()
        {

        }

        internal ChatMessage(XElement message)
        {
            this.Sender = new Jid(message.Attribute("from").Value);
            this.Recepient = new Jid(message.Attribute("to").Value);
            this.Message = message.Element("body").Value;
            if (message.Attribute("timestamp") == null)
            {
                this.Timestamp = DateTime.Now;
            }
        }

        internal void Save(XElement element)
        {
            element.Add(
                new XElement("message",
                new XAttribute("from", this.Sender),
                new XAttribute("to", this.Recepient),
                new XAttribute("type", MessageType),
                new XAttribute("timestamp", this.Timestamp),
                    new XElement("body", this.Message)));
        }
    }
}
